var app = require('../app');
    template = require('../../modules/template'),
    tabControl = require('../../modules/tabControl'),
    formMod = require('../../modules/form'),
    cookie = require('../../modules/$.cookie'),
    call_pass = $('.call_pass').val(),
    loading = require('../../modules/loading'),
    DOMAIN = document.domain,
    ajaxUrl = '',//本地调试 假接口提交置空
    DefendantMobileObj = {},
    CLIENTID = $.cookie('clientId'),
    lockfas = false,
    ajaxPromise = function(param){
        return new Promise(function(resolve, reject){
            $.ajax({
                url: ajaxUrl + '/apis' + param.url,
                type: param.data || 'get',
                data: param.data || '',
                dataType: 'xml',
                success: function(res){
                    resolve(res);
                },
                error: function(error){
                    // toastr.error('网络连接错误，请稍后重试！');
                    reject(error); 
                }
            });
            
        }).catch((e) => {
            //throw new Error;
        });

    },
    lock = {
        getCaseInfo: false
    };
     //分机号拖拽
     var bool=false;  
     var offsetX=0;  
     var offsetY=0;  
window.slideLeft = window.slideLeft ? window.slideLeft : {};

$('body')
    .on('change','#call_type',function(){
        window.location.href = '/incoming/index?type=' + $(this).val();
    })
    //关闭侧边栏
    .on('click','[role-close="slide"]',function(){
        // slideLeft = null;
        $('[role-side="left"] .ui-call').css({
            transform: 'translate(100%,0)'
        });
        $('[role-side="left"]').fadeOut(500);
        $('.ui-call-extension').fadeOut(500);
        $('.ui-call-extension').css({
            transform: 'translate(-100%,0)'
        }); 
        ChangeWorkMode(0);//0呼入，1呼出
        setTimeout(function(){
            window.location.href = window.location.href;
        },2000)
        
    })
    //常态呼出关闭
    .on('click','[role-close="slidedefault"]',function(){
        // slideLeft = null;
        $('[role-side="left"] .ui-call').css({
            transform: 'translate(100%,0)'
        });
        $('[role-side="left"]').fadeOut(500);
        $('.ui-call-extension').fadeOut(500);
        $('.ui-call-extension').css({
            transform: 'translate(-100%,0)'
        }); 
        window.location.href = window.location.href;
        
    })
    //获取被告手机号
    .on('mouseenter','[role-alertbox="select"]',function(){
            
        var that = $(this),
            roleCall = that.attr('role-call');
            caseId = that.attr('data-caseid');
        if(DefendantMobileObj[caseId] && DefendantMobileObj[caseId]._array.length > 0){
            return that.html(DefendantMobileObj[caseId]._html);;
        }

        DefendantMobileObj[caseId] = new GetDefendantMobile(caseId);
        DefendantMobileObj[caseId].getData(that);

    })

    //呼出切换案件资料
    .on('click', '.caseCheckInfo-main-nav-li', function(){
        var fileSrc = $(this).attr('filepath')
        $('.showFile').attr('src',fileSrc)
        $('.caseCheckInfo-main-nav-li-img-box').removeClass('caseCheckInfo-main-nav-li-img-box-checked');
        $('.caseCheckInfo-main-nav-li-name').removeClass('caseCheckInfo-main-nav-li-name-checked');
        $(this).children(".caseCheckInfo-main-nav-li-img-box").addClass('caseCheckInfo-main-nav-li-img-box-checked');
        $(this).children(".caseCheckInfo-main-nav-li-name").addClass('caseCheckInfo-main-nav-li-name-checked');
    })
    
    //分机号关闭
    .on('click', '.ui-call-extension-close', function(){
        $('.ui-call-extension').fadeOut(500);
        $('.ui-call-extension').css({
            transform: 'translate(-100%,0)'
        }); 
    })
    .on('mousedown', '.ui-call-extension', function(e){
        if(e.target.className =='ui-call-extension-close'){ return;}
        bool=true;  
        offsetX = e.offsetX;  
        offsetY = e.offsetY;  
        $(this).css('cursor','move');  
    })
    $(document).mousemove(function(e){
        if(!bool)  
        return; 
        $('.ui-call-extension').css('transition','none');
        var x = e.clientX-offsetX;  
        var y = e.clientY-offsetY;  
        $(".ui-call-extension").css("left", x);  
        $(".ui-call-extension").css("top", y);  
    }).mouseup(
        function () {
            bool = false;
            $('.ui-call-extension').css('transition','all .5s ease-In');
    });
//获取被告手机号
class GetDefendantMobile {
    constructor(caseId){
        this.caseId = caseId;
        this._array = [];
    }
    getData(templateBox){
        
        var that = this;
        $.ajax({
            url: ajaxUrl + '/mediate/defendantMobile',
            data: {
                "case_id": that.caseId
            },
            type: "post",
            dataType: 'json',
            success: function(res){
                if(res.code == 200){
                    
                    that._array = res.data;
                    var _html = '',
                        i = 0,
                        num = res.data;
                    for(i = 0; i < num.length;i++){
                        _html += `<option value="${num[i].mobile}" mobile_id="${num[i].mobile_id}" ext_mobile="${num[i].ext_mobile}" is_ht="${num[i].val}" is_call="${num[i].is_call}">${num[i].val}</option>`
                    }
                    

                    _html = '<option value="" style="display: none;" disabled selected>呼叫被告</option>' + _html;
                    DefendantMobileObj[that.caseId]._html = _html;
                    templateBox.html(_html);
                }else{
                    
                    toastr.error(res.message); 
                }
            }
        })
    }
}
function ChangeWorkMode(type,callback){
    loading.showLoading({
        type: 1,
        tip: '请稍后...'
    })
    ajaxPromise({
        url: `/api/Softphone/ChangeWorkMode?clientId=${CLIENTID}&type=${type}`//0呼入，1呼出
    }).then(function(res){
    }).catch(function(){
        toastr.error('模式切换失败');
        loading && loading.hideLoading();
    })
}

//存储调解记录
formMod.listen('/apipublic/addMediateRecord',{
    ajaxBefore: function(validResutl){
        var caseId = $.cookie('caseId'),
            mobileId = $.cookie('mobileId'),
            type = $.cookie('type'),
            FileName = $.cookie('FileName_addMediateRecord'),
            write = $.cookie('write'),
            callTime = $.cookie('calloutTime'),// 呼出时间
            callendTime = $.cookie('callendTime'),// 呼出结束时间
            isHt = $.cookie('isHt');
        $(validResutl).find('[name="type"]').val(type);
        $(validResutl).find('[name="case_id"]').val(caseId);
        $(validResutl).find('[name="file_name"]').val(FileName);
        $(validResutl).find('[name="call_time"]').val(callTime);
        $(validResutl).find('[name="call_end_time"]').val(callendTime);
        if(type == 2){
            $(validResutl).find('[name="mobile_id"]').val(mobileId);
        }else{
            $(validResutl).find('[name="mobile_id"]').val('');
        }
        $(validResutl).find('[name="is_ht"]').val(isHt);
        $(validResutl).find('[name="write"]').val(write);
       

    },
    validError: function(validResutl){
        var item  = validResutl.element;
        if(item.attr('name')=='desc'){
            if(validResutl.valid == 'notempty'){
                toastr.info('请填写备注信息');
            }
        }
        if(item.attr('name')=='result'){
            if(validResutl.valid == 'notempty'){
                toastr.info('请选择调解结果');
            }
        }
        if(item.attr('name')=='time'){
            if(validResutl.valid == 'notempty'){
                toastr.info('请填写下次调解时间');
            }
        }
    },
    cleanup: function(item){},
    success: function(result){
        var res = result.data;
        if(res.code == 200){
            toastr.success('提交成功');
            //保存状态确认
            window.slideLeft.outHtmls('saved');
            $.cookie('FileName_addMediateRecord', null, { expires: -1, path: '/', domain: DOMAIN });
            // ChangeWorkMode(0);//0呼入，1呼出
        }else{
            toastr.error(res.message);
            // 本地调试
            //window.slideLeft.outHtmls('saved');
        }

    },
    error: function(){}
});